<template>
  <div>
    <div>
        <el-radio-group v-model="data.type">
            <el-radio :label="'device'">设备监听</el-radio>
        </el-radio-group>
    </div>
    <div v-if="data.type=='device'">
      <el-row>
        <el-col :span="8"><el-button plain @click="openProductSelector" size="mini">选择产品:{{selectedProduct.name}}</el-button></el-col>
        <el-col :span="8"><el-button v-if="selectedProduct.code" plain @click="openDeviceSelector" size="mini">选择设备:{{selectedDeviceName}}</el-button></el-col>
        <el-col :span="8">
        </el-col>
      </el-row>
      <ProductSelector v-if="showProductSelector" @productSelected="onProductSelected"></ProductSelector>
      <DeviceSelector v-if="showDeviceSelector && selectedProduct.code" @deviceSelected="onDeviceSelected" :param="deviceParam"></DeviceSelector>
      <el-row>
        <el-col :span="2">
          条件:
        </el-col>
        <el-col :span="22">
           <el-row v-for="cond in data.conditions" :key="cond.identifier">
            <el-col :span="22">
              <ListenerCondition :data="cond" :types="modelItems" :properties="properties" :events="events" :services="services"></ListenerCondition>
            </el-col>
            <el-col :span="2" style="padding-left:5px">
              <el-button plain @click="delCondition(cond)" size="mini">-</el-button>
            </el-col>
          </el-row>
          <el-button v-if="selectedProduct.code" plain @click="addCondition" size="mini">+</el-button>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
  import DeviceSelector from '../device/DeviceSelector.vue'
  import ProductSelector from '../product/ProductSelector.vue'
  import ListenerCondition from './ListenerCondition.vue'
  import {
    GetThingModel,
    GetProduct
  } from '../../api/productApi'
  import{GetDeviceByDn} from '@/api/deviceApi'
  export default {
    name: 'Listener',
    props: {
     data:{
         type: Object,
         default: () => {
            return {
                type: '',
                topic:'',
                conditions: []
            }
         }
     }
    },
    data() {
      return {
        showProductSelector: false,
        selectedProduct: {},
        selectedDevice: {},
        showDeviceSelector: false,
        selectedDeviceName: '所有设备',
        showConditionSelector: false,
        properties: [],
        events: [],
        services: [],
        modelItems: [],
        deviceParam: {},
      }
    },
    // 注册组件
    components: {
      ProductSelector,
      DeviceSelector,
      ListenerCondition
    },
    created() {
      this.init();
    },
    watch:{
      data(){
        this.init();
      }
    },
    methods: {
      init(){
        if(this.data.type=='device' && this.data.topic){
          let pkDn=this.data.topic.replace('/sys/','').replace('/s/#','').split('/');
          let pk=pkDn[0];
          this.getProduct(pk);
          let dn=pkDn[1];
          if(dn!='+'){
            GetDeviceByDn(pk,dn).then(res=>{
              this.selectedDeviceName=res.deviceName;
            })
          }
        }
      },
      openProductSelector(){
        this.showProductSelector=!this.showProductSelector
      },
      openDeviceSelector(){
        this.showDeviceSelector=!this.showDeviceSelector
      },
      onProductSelected(product){
        this.selectedProduct=product;
        this.showProductSelector=false;
        this.deviceParam.pk=product.code;
        this.data.conditions.forEach(c=>{
          c.parameters=[];
        });
        this.buildTopic();
        this.getThingModel(product.code);
        this.selectedDeviceName='所有设备';
      },
      onDeviceSelected(device){
        this.selectedDeviceName=device.deviceName
        this.selectedDevice=device;
        this.showDeviceSelector=false
        this.buildTopic();
      }, 
      buildTopic(){
        if(!this.selectedProduct.code){
          return;
        }
        if(this.selectedDevice.deviceName){
          this.data.topic='/sys/'+this.selectedProduct.code+'/'+this.selectedDevice.deviceName+'/s/#';
        }else{
          this.data.topic='/sys/'+this.selectedProduct.code+'/+/s/#';
        }
      },
      getThingModel(pk) {
        this.loading = true
        GetThingModel(pk)
        .then(res => {
          this.initThingModel(res)
        })
      },
      getProduct(pk){
        GetProduct(pk).then(res=>{
          this.selectedProduct = res
          this.getThingModel(pk);
        })
      },
      initThingModel(res){
        this.modelItems=[];
        this.properties=[];
        this.events=[];
        this.services=[];

        this.modelItems.push({
          name: '通配',
          items: [
            {
              type: 'event',
              identifier: 'event:*',
              name: '任意事件上报'
            },
            {
              type: 'service_reply',
              identifier: 'service_reply:*',
              name: '任意服务回复'
            },
            {
              type: 'property',
              identifier: 'property:*',
              name: '任意属性上报'
            }
          ]
        });

        let items=[];
        this.modelItems.push({
          name: '精确匹配',
          items: items
        });
        items.push({
          type: 'property',
          identifier: 'post',
          name: '属性上报'
        });
        res.model.events.forEach(s=>{
          items.push({
            type: 'event',
            identifier: s.identifier,
            name: s.name
          });
        });
        res.model.services.forEach(s=>{
          items.push({
            type: 'service',
            identifier: s.identifier,
            name: s.name
          });
        });

        res.model.properties.forEach(p=>{
          this.properties.push({
            identifier: p.identifier,
            name: p.name,
          })
        });

        res.model.events.forEach(s=>{
          let items=[];
          this.events.push({
            identifier:  s.identifier,
            items: items
          })

          s.outputData.forEach(p=>{
            items.push({
              identifier: p.identifier,
              name: p.name
            })
          })
        });

        res.model.services.forEach(s=>{
          let items=[];
          this.services.push({
            identifier:  s.identifier,
            items: items
          })

          s.outputData.forEach(p=>{
            items.push({
              identifier: p.identifier,
              name: p.name
            })
          })
        });
        
      },
      addCondition(){
        this.showConditionSelector= true
        this.data.conditions.push({
          id:Math.random(),
          type: '',
          identifier: '',
          parameters: []
        })
      },
      delCondition(cond){
        let index= this.data.conditions.findIndex((c)=>{
          return  c.id==cond.id
        })
        this.data.conditions.splice(index,1);
      }
    }
  }
</script>

<style>
</style>
